#!/usr/bin/env node

/**
 * 示例构建脚本
 * 用于 CI/CD 流程中的构建阶段
 */

const fs = require('fs');
const path = require('path');

console.log('🔨 开始构建过程...');
console.log('=' .repeat(50));

/**
 * 构建步骤函数
 */
function buildStep(stepName, action) {
  console.log(`📦 ${stepName}`);
  console.log('-'.repeat(30));
  
  try {
    action();
    console.log(`✅ ${stepName} 完成`);
  } catch (error) {
    console.log(`❌ ${stepName} 失败: ${error.message}`);
    process.exit(1);
  }
  
  console.log('');
}

/**
 * 主构建流程
 */
function runBuild() {
  const startTime = Date.now();
  
  // 步骤 1: 清理构建目录
  buildStep('清理构建目录', () => {
    const distDir = path.join(__dirname, 'dist');
    if (fs.existsSync(distDir)) {
      fs.rmSync(distDir, { recursive: true, force: true });
      console.log('🗑️  删除旧的 dist 目录');
    }
    fs.mkdirSync(distDir, { recursive: true });
    console.log('📁 创建新的 dist 目录');
  });
  
  // 步骤 2: 复制源文件
  buildStep('复制源文件', () => {
    const sourceFiles = ['index.js', 'package.json'];
    const distDir = path.join(__dirname, 'dist');
    
    sourceFiles.forEach(file => {
      if (fs.existsSync(file)) {
        fs.copyFileSync(file, path.join(distDir, file));
        console.log(`📄 复制 ${file}`);
      }
    });
  });
  
  // 步骤 3: 生成构建信息
  buildStep('生成构建信息', () => {
    const buildInfo = {
      buildTime: new Date().toISOString(),
      version: '1.0.0',
      nodeVersion: process.version,
      platform: process.platform,
      arch: process.arch,
      buildNumber: Math.floor(Math.random() * 10000),
      gitCommit: 'abc123def456', // 模拟 git commit hash
      environment: process.env.NODE_ENV || 'production'
    };
    
    const buildInfoPath = path.join(__dirname, 'dist', 'build-info.json');
    fs.writeFileSync(buildInfoPath, JSON.stringify(buildInfo, null, 2));
    console.log('📋 生成 build-info.json');
    console.log(`🏷️  构建版本: ${buildInfo.version}`);
    console.log(`🔢 构建编号: ${buildInfo.buildNumber}`);
  });
  
  // 步骤 4: 压缩和优化
  buildStep('压缩和优化', () => {
    console.log('🗜️  模拟代码压缩...');
    // 模拟压缩过程
    for (let i = 0; i < 3; i++) {
      setTimeout(() => {}, 100);
    }
    console.log('📉 代码大小减少 25%');
    console.log('⚡ 性能优化完成');
  });
  
  // 步骤 5: 生成部署清单
  buildStep('生成部署清单', () => {
    const manifest = {
      name: 'ci-demo-project',
      version: '1.0.0',
      files: [
        'index.js',
        'package.json',
        'build-info.json'
      ],
      entrypoint: 'index.js',
      healthcheck: '/health',
      port: 3000
    };
    
    const manifestPath = path.join(__dirname, 'dist', 'manifest.json');
    fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
    console.log('📜 生成 manifest.json');
  });
  
  const endTime = Date.now();
  const buildDuration = ((endTime - startTime) / 1000).toFixed(2);
  
  console.log('🎉 构建完成！');
  console.log('=' .repeat(50));
  console.log('📊 构建统计:');
  console.log(`⏱️  构建时间: ${buildDuration} 秒`);
  console.log(`📁 输出目录: ${path.join(__dirname, 'dist')}`);
  console.log(`📦 构建产物:`);
  
  // 列出构建产物
  const distDir = path.join(__dirname, 'dist');
  if (fs.existsSync(distDir)) {
    const files = fs.readdirSync(distDir);
    files.forEach(file => {
      const filePath = path.join(distDir, file);
      const stats = fs.statSync(filePath);
      console.log(`   - ${file} (${(stats.size / 1024).toFixed(2)} KB)`);
    });
  }
  
  console.log('✨ 构建流程全部完成！');
}

// 运行构建
runBuild();